package com.aop.demo.aop;

import com.aop.demo.bean.User;
import com.aop.demo.service.UserValidator;
import com.aop.demo.service.impl.UserValidatorImpl;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author H
 * @date 2023/1/1
 */
@Component
@Aspect
public class MyAspect {

    @DeclareParents(
            value = "com.aop.demo.service.impl.UserServiceImpl",
            defaultImpl = UserValidatorImpl.class
    )
    public UserValidator userValidator;

    @Pointcut("execution(* com.aop.demo.service.impl.UserServiceImpl.print(..))")
    public void pointCut() {
    }

    @Before("pointCut() && args(user)")
    public void before(JoinPoint joinPoint, User user) {
        System.out.println("before开始......");
        Object[] args = joinPoint.getArgs();
        for (Object arg : args) {
            System.out.println(arg);
        }
        System.out.println("before结束......");
    }

    @After("pointCut()")
    public void after() {
        System.out.println("after......");
    }

    @Around("pointCut()")
    public void around(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("around before......");
        // 回调目标对象的原有方法
        pj.proceed();
        System.out.println("around after......");
    }

    @AfterReturning("pointCut()")
    public void afterReturning() {
        System.out.println("afterReturning");
    }

    @AfterThrowing("pointCut()")
    public void afterThrowing() {
        System.out.println("afterThrowing");
    }
}
